package com.yloveg.base;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.yloveg.entity.Suser;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


/**
* 自定义拦截器
* @author Administrator
*
*/
public class SecurityInterceptor extends HandlerInterceptorAdapter {
    @Override
    public void afterCompletion(HttpServletRequest request,
        HttpServletResponse response, Object handler, Exception ex)
        throws Exception {
        // TODO Auto-generated method stub 
    	System.out.println("登陆验证afterCompletion");
        super.afterCompletion(request, response, handler, ex);
    }

    @Override
    public void afterConcurrentHandlingStarted(HttpServletRequest request,
        HttpServletResponse response, Object handler) throws Exception {
        // TODO Auto-generated method stub 
    	System.out.println("登陆验证afterConcurrentHandlingStarted");
    	HttpSession session = request.getSession(true);
    	Suser Suser = (Suser) session.getAttribute(BaseController.SESSION_USER);
        super.afterConcurrentHandlingStarted(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request,
        HttpServletResponse response, Object handler, ModelAndView modelAndView)
        throws Exception {
        // TODO Auto-generated method stub 
    	System.out.println("登陆验证postHandle");
        super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {
        System.out.println("登陆验证preHandle");
    	HttpSession session = request.getSession(true);
        Suser Suser = (Suser) session.getAttribute(BaseController.SESSION_USER);
        String requestURI = request.getRequestURI();
        System.out.println("请求地址"+requestURI);
        // session 用户是否登陆 
/*        if(requestURI.contains("/user/")) {
        	return true;
        }*/
        if (null == Suser) {
        	String url = request.getProtocol();
        	String head="";
        	if(!url.equals("HTTP/1.1")){
        		head="https://"+request.getServerName();
        	}
        	
            response.sendRedirect(head+request.getContextPath() +"/user/login");
            return false;
        }

        return true;
    }
}
